package com.lv.common.utils;


import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.format.DateUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lv.common.imp.OnPositionListener;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by uctimes on 2016/10/25.
 */
public class SaveImageUtils {


    /**
     * 将本地图片转成Bitmap
     *
     * @param path 已有图片的路径
     * @return
     */
    public static Bitmap picToBitmap(String path) {
        Bitmap bitmap = null;
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));
            bitmap = BitmapFactory.decodeStream(bis);
            bis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }


//    public static Bitmap loadBitmapFromView(View v) {
//        int w = v.getWidth();
//        int h = v.getHeight();
//
//        Bitmap bmp = null;
//        bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
//        Canvas c = new Canvas(bmp);
//        Drawable bgDrawable = v.getBackground();
//        if (bgDrawable != null) {
//            bgDrawable.draw(c);
//        } else {
//            c.drawColor(Color.WHITE);
//        }
////        c.drawColor(Color.WHITE);
//        /** 如果不设置canvas画布为白色，则生成透明 */
//
////        v.layout(0, 0, w, h);
//        v.draw(c);
//
//        return bmp;
//    }

    /**
     * 高效的获取View的裁剪区
     *
     * @param view            需要处理的View
     * @param crop            裁剪区域
     * @param downscaleFactor 缩放参数
     * @return
     */
    public static Bitmap getDownscaledBitmapForView(View view, Rect crop, float downscaleFactor) {

        View screenView = view;

        int width = (int) (crop.width() * downscaleFactor);
        int height = (int) (crop.height() * downscaleFactor);
        float dx = -crop.left * downscaleFactor;
        float dy = -crop.top * downscaleFactor;

        if (width * height <= 0) {
            return null;
        }
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);//准备图片
        Canvas canvas = new Canvas(bitmap);//将bitmap作为绘制画布
        Matrix matrix = new Matrix();
        matrix.preScale(downscaleFactor, downscaleFactor);
        matrix.postTranslate(dx, dy);
        canvas.setMatrix(matrix);//设置matrix
        screenView.draw(canvas);//讲View特定的区域绘制到这个canvas（bitmap）上去，
        return bitmap;//得到最新的画布
    }


    public static Bitmap convertViewToBitmap(View view) {
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        int w = view.getWidth();
        int h = view.getHeight();
        Bitmap bmp = null;
        bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);
        Drawable bgDrawable = view.getBackground();
        if (bgDrawable != null) {
            bgDrawable.draw(c);
        } else {
            c.drawColor(Color.WHITE);
        }
//        c.drawColor(Color.WHITE);
        /** 如果不设置canvas画布为白色，则生成透明 */

//        v.layout(0, 0, w, h);
        view.draw(c);
        return bmp;
    }

    /**
     * 保存二维码到本地相册
     */
    public static void saveImageToPhotos(Context context, Bitmap bmp, OnPositionListener positionListener) {
        // 首先保存图片
        File appDir = new File(MyUtils.getSDPath(context), "suyiyong_o");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
//        String mimeType = getMimeType(file);

        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
//        // 最后通知图库更新
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        context.sendBroadcast(intent);
//        if (showToast) {
//            ToastKt.showToast(context,"图片保存成功,请到相册查找");
//        }
        positionListener.onClick(-1);
    }
    /**
     * 保存到相册
     *
     * @param context
     * @param image
     */
    public static void savePicToPhone(Context context, Bitmap image, OnPositionListener mPositionListener) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            saveImageToGallery2(context, image, mPositionListener);
        } else {
            saveImageToPhotos(context, image, mPositionListener);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    public static void saveImageToGallery2(Context context, Bitmap image, OnPositionListener onPositionListener) {
        Long mImageTime = System.currentTimeMillis();
//        String imageDate = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date(mImageTime));
//        String SCREENSHOT_FILE_NAME_TEMPLATE = "winetalk_%s.png";//图片名称，以"winetalk"+时间戳命名
//        String mImageFileName = String.format(SCREENSHOT_FILE_NAME_TEMPLATE, imageDate);
        File appDir = new File(MyUtils.getSDPath(context), "suyiyong_o");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = mImageTime + ".jpg";
//        File file = new File(appDir, fileName);
        final ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES
                + File.separator + "suyiyong_o"); //Environment.DIRECTORY_SCREENSHOTS:截图,图库中显示的文件夹名。"dh"
        values.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
//        values.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
        values.put(MediaStore.MediaColumns.DATE_ADDED, mImageTime / 1000);
        values.put(MediaStore.MediaColumns.DATE_MODIFIED, mImageTime / 1000);
        values.put(MediaStore.MediaColumns.DATE_EXPIRES, (mImageTime + DateUtils.DAY_IN_MILLIS) / 1000);
        values.put(MediaStore.MediaColumns.IS_PENDING, 1);

        ContentResolver resolver = context.getContentResolver();
        final Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        try {
            // First, write the actual data for our screenshot
            try (OutputStream out = resolver.openOutputStream(uri)) {
                if (!image.compress(Bitmap.CompressFormat.PNG, 100, out)) {
                    throw new IOException("Failed to compress");
                }
            }
            // Everything went well above, publish it!
            values.clear();
            values.put(MediaStore.MediaColumns.IS_PENDING, 0);
            values.putNull(MediaStore.MediaColumns.DATE_EXPIRES);
            resolver.update(uri, values, null, null);
//            Toast.makeText(context,context.getString(R.string.qrsavesuccess),
//                    Toast.LENGTH_SHORT).show();
//            if (isShowToast) {
//                ToastUtils.showShort("图片保存成功,请到相册查找");
////                Toast.makeText(context, "图片保存成功,请到相册查找", Toast.LENGTH_SHORT).show();
//            }
            onPositionListener.onClick(-1);
//            mHandler.obtainMessage(SAVE_SUCCESS).sendToTarget();
        } catch (IOException e) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                resolver.delete(uri, null);
            }
//            if (isShowToast) {
//                ToastKt.showToast(context,"图片保存成功,请到相册查找");
////                Toast.makeText(context, "图片保存成功,请到相册查找", Toast.LENGTH_SHORT).show();
//            }
            onPositionListener.onClick(-1);
//            mHandler.obtainMessage(SAVE_FAILURE).sendToTarget();

        }
    }

    private static final int SAVE_SUCCESS = 0;//保存图片成功
    private static final int SAVE_FAILURE = 1;//保存图片失败
    private static final int SAVE_BEGIN = 2;//开始保存图片

    public static Bitmap compressImage(Bitmap image, int maxKB) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 90;
        while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset(); // 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }


    /**
     * 把上面获得的bitmap传进来就可以得到圆角的bitmap了
     */
//    public static Bitmap bitmapInBitmap(Bitmap bitmap) {
//        Bitmap tempBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
//        Canvas canvas = new Canvas(tempBitmap);
//
//        //图像上画矩形
//        Paint paint = new Paint();
//        paint.setColor(Color.TRANSPARENT);
//        paint.setStyle(Paint.Style.STROKE);//不填充
//        paint.setStrokeWidth(10);  //线的宽度
//        canvas.drawRect(10, 20, 100, 100, paint);
////        imageView.setImageBitmap(tempBitmap);
//
//        //画中画
//        Paint photoPaint = new Paint(); // 建立画笔
//        photoPaint.setDither(true); // 获取跟清晰的图像采样
//        photoPaint.setFilterBitmap(true);// 过滤一些
//
//        Rect src = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());// 创建一个指定的新矩形的坐标
//        Rect dst = new Rect(0, 0, 300, 350);// 创建一个指定的新矩形的坐标
//        canvas.drawBitmap(tempBitmap, src, dst, photoPaint);// 将photo 缩放或则扩大到
//        return getRoundedCornerBitmap(tempBitmap);
//    }

    /**
     * 生成圆角图片
     */
    public static Bitmap getRoundedCornerBitmap(Context context, Bitmap bitmap) {
        try {
            Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                    bitmap.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(output);
            final Paint paint = new Paint();
            final Rect rect = new Rect(0, 0, bitmap.getWidth(),
                    bitmap.getHeight());
            final RectF rectF = new RectF(new Rect(0, 0, bitmap.getWidth(),
                    bitmap.getHeight()));
            //设置圆角大小
            final float roundPx = DensityUtil.dip2px(context, 8);
            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(Color.BLACK);
            canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
            final Rect src = new Rect(0, 0, bitmap.getWidth(),
                    bitmap.getHeight());
            canvas.drawBitmap(bitmap, src, rect, paint);
            return output;
        } catch (Exception e) {
            return bitmap;
        }
    }

    /**
     * 获得圆角图片的方法
     *
     * @param bitmap  需处理的图片
     * @param roundPx 圆角的弧率
     * @return
     */
//    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
//
//        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
//        Canvas canvas = new Canvas(output);
//
//        final int color = 0xff424242;
//        final Paint paint = new Paint();
//        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
//        final RectF rectF = new RectF(rect);
//
//        paint.setAntiAlias(true);
//        canvas.drawARGB(0, 0, 0, 0);
//        paint.setColor(color);
//        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
//
//        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
//        canvas.drawBitmap(bitmap, rect, rect, paint);
//
//        return output;
//    }

    /**
     * 保存图片到本地
     */
    public static void saveImageToPhotosLocal(Context context, Bitmap bmp, String temp, boolean showToast) {
        // 首先保存图片
        File appDir = new File(MyUtils.getSDPath(context), "suyiyong_o/" + temp);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
//        String mimeType = getMimeType(file);

        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (showToast) {
//        // 最后通知图库更新
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(file);
            intent.setData(uri);
            context.sendBroadcast(intent);
            Toast.makeText(context, "图片保存成功,请到相册查找", Toast.LENGTH_SHORT).show();
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    public static void saveImageToGalleryLocal(Context context, Bitmap image, String temp, boolean isShowToast) {
        Long mImageTime = System.currentTimeMillis();
//        String imageDate = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date(mImageTime));
//        String SCREENSHOT_FILE_NAME_TEMPLATE = "winetalk_%s.png";//图片名称，以"winetalk"+时间戳命名
//        String mImageFileName = String.format(SCREENSHOT_FILE_NAME_TEMPLATE, imageDate);
        File appDir = new File(MyUtils.getSDPath(context), "suyiyong_o/" + temp);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = mImageTime + ".jpg";
//        File file = new File(appDir, fileName);
        final ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES
                + File.separator + "suyiyong_o/" + temp); //Environment.DIRECTORY_SCREENSHOTS:截图,图库中显示的文件夹名。"dh"
        values.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
//        values.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
        values.put(MediaStore.MediaColumns.DATE_ADDED, mImageTime / 1000);
        values.put(MediaStore.MediaColumns.DATE_MODIFIED, mImageTime / 1000);
        values.put(MediaStore.MediaColumns.DATE_EXPIRES, (mImageTime + DateUtils.DAY_IN_MILLIS) / 1000);
        values.put(MediaStore.MediaColumns.IS_PENDING, 1);

        ContentResolver resolver = context.getContentResolver();
        final Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        try {
            // First, write the actual data for our screenshot
            try (OutputStream out = resolver.openOutputStream(uri)) {
                if (!image.compress(Bitmap.CompressFormat.PNG, 100, out)) {
                    throw new IOException("Failed to compress");
                }
            }
            // Everything went well above, publish it!
            values.clear();
            values.put(MediaStore.MediaColumns.IS_PENDING, 0);
            values.putNull(MediaStore.MediaColumns.DATE_EXPIRES);
            resolver.update(uri, values, null, null);
//            Toast.makeText(context,context.getString(R.string.qrsavesuccess),
//                    Toast.LENGTH_SHORT).show();
            if (isShowToast) {
                ToastUtils.showShort("图片保存成功,请到相册查找");
//                Toast.makeText(context, "图片保存成功,请到相册查找", Toast.LENGTH_SHORT).show();
            }
//            mHandler.obtainMessage(SAVE_SUCCESS).sendToTarget();
        } catch (IOException e) {
            if (isShowToast) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    resolver.delete(uri, null);
                }
                ToastUtils.showShort("图片保存成功,请到相册查找");

//                Toast.makeText(context, "图片保存成功,请到相册查找", Toast.LENGTH_SHORT).show();
            }
//            mHandler.obtainMessage(SAVE_FAILURE).sendToTarget();

        }
    }

    /**
     * @param viewGroup viewGroup
     * @return Bitmap
     */
    public static Bitmap getViewGroupBitmapNoBg(ViewGroup viewGroup) {
        // 创建对应大小的bitmap(重点)
        Bitmap bitmap = Bitmap.createBitmap(viewGroup.getWidth(), viewGroup.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        viewGroup.draw(canvas);
        return bitmap;
    }

    /**
     * @param viewGroup viewGroup
     * @return Bitmap
     */
    public static Bitmap getViewGroupBitmap(ViewGroup viewGroup) {
        viewGroup.setBackground(new ColorDrawable(Color.TRANSPARENT));
        viewGroup.invalidate();
        // 创建对应大小的bitmap(重点)
        Bitmap bitmap = Bitmap.createBitmap(viewGroup.getWidth(), viewGroup.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        viewGroup.draw(canvas);
        return bitmap;
    }

    /**
     * @param viewGroup viewGroup
     * @return Bitmap
     */
    public static Bitmap getViewGroupBitmap(Activity activity, ViewGroup viewGroup) {
        View screenView = activity.getWindow().getDecorView();
        screenView.setDrawingCacheEnabled(true);
        screenView.buildDrawingCache();

        //获取屏幕整张图片
        Bitmap bitmap = screenView.getDrawingCache();

        if (bitmap != null) {
            //需要截取的长和宽
            int outWidth = viewGroup.getWidth();
            int outHeight = viewGroup.getHeight();

            //获取需要截图部分的在屏幕上的坐标(view的左上角坐标）
            int[] viewLocationArray = new int[2];
            viewGroup.getLocationOnScreen(viewLocationArray);

            //从屏幕整张图片中截取指定区域
            bitmap = Bitmap.createBitmap(bitmap, viewLocationArray[0], viewLocationArray[1], outWidth, outHeight);
        }
        return bitmap;
    }

    public static String saveBitmap(Context context, Bitmap bitmap, String temp) {
        // 首先保存图片
        Long mImageTime = System.currentTimeMillis();
        File appDir = new File(MyUtils.getSDPath(context), "suyiyong_o/" + temp);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = mImageTime + ".jpg";
        File file = new File(appDir, fileName);
        ImageUtils.save(
                bitmap,
                file,
                Bitmap.CompressFormat.JPEG);
        return file.getPath();
    }

    public static void deleteAllInDir(Context context, String temp) {
        File appDir = new File(MyUtils.getSDPath(context), "suyiyong_o/" + temp);
        FileUtils.deleteAllInDir(appDir);
    }

    public static String saveBitmapPNG(Context context, Bitmap bitmap, String temp) {
        // 首先保存图片
        Long mImageTime = System.currentTimeMillis();
        File appDir = new File(MyUtils.getSDPath(context), "suyiyong_o/" + temp);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = mImageTime + ".png";
        File file = new File(appDir, fileName);
        ImageUtils.save(
                bitmap,
                file,
                Bitmap.CompressFormat.PNG);
        return file.getPath();
    }
}
